package com.renwei.yunlong.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.ProtocolActivity;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpPresenter;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.FormatUtil;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.lang.ref.WeakReference;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 注册页面
 * <p>
 * Created by Administrator on 2017/8/22.
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {


    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.iv_service)
    ImageView ivService;
    @Bind(R.id.tv_service)
    TextView tvService;
    @Bind(R.id.iv_service_bottom)
    ImageView ivServiceBottom;
    @Bind(R.id.rl_service)
    RelativeLayout rlService;
    @Bind(R.id.iv_owner)
    ImageView ivOwner;
    @Bind(R.id.tv_owner)
    TextView tvOwner;
    @Bind(R.id.iv_owner_bottom)
    ImageView ivOwnerBottom;
    @Bind(R.id.rl_owner)
    RelativeLayout rlOwner;
    @Bind(R.id.et_enterprise)
    EditText etEnterprise;
    @Bind(R.id.view_enterprise)
    View viewEnterprise;
    @Bind(R.id.et_name)
    EditText etName;
    @Bind(R.id.view_name)
    View viewName;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.view_phone)
    View viewPhone;
    @Bind(R.id.et_verification)
    EditText etVerification;
    @Bind(R.id.btn_vercode)
    Button btnVercode;
    @Bind(R.id.register_center)
    LinearLayout registerCenter;
    @Bind(R.id.et_pwd)
    EditText etPwd;
    @Bind(R.id.view_pwd)
    View viewPwd;
    @Bind(R.id.et_determine_pwd)
    EditText etDeterminePwd;
    @Bind(R.id.cb_protocol)
    CheckBox cbProtocol;
    @Bind(R.id.tv_protocol)
    TextView tvProtocol;
    @Bind(R.id.btn_register)
    Button btnRegister;
    private HttpPresenter hp;//网络

    private RegisterHandler myHandler = new RegisterHandler(this);

    private String companyTypeStr = "2";//企业类型

    private String userName;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        initData();
    }

    private void initData() {
        btnVercode = (Button) findViewById(R.id.btn_vercode);
        tvTitle.setText("注册");
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        tvProtocol.setOnClickListener(this);
        rlService.setOnClickListener(this);
        rlOwner.setOnClickListener(this);
        btnVercode.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        etPwd.setHint(Html.fromHtml("设置密码  <font><small>6~12位数字、字母的组合</small></font>"));
        etDeterminePwd.setHint(Html.fromHtml("确认密码   <font><small>6~12位数字、字母的组合</small></font>"));

        etEnterprise.setFilters(new InputFilter[]{AppHelper.emojiFilter});
        etName.setFilters(new InputFilter[]{AppHelper.emojiFilter});
        etPwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20), AppHelper.emojiFilter});
        etDeterminePwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20), AppHelper.emojiFilter});

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_protocol:
                startActivityForResult(new Intent(this, ProtocolActivity.class), 100);
                break;
            case R.id.rl_service://服务商
                companyTypeStr = "2";//标记号
                ivService.setImageResource(R.mipmap.service_selected);
                tvService.setTextColor(getResources().getColor(R.color.blue_color));
                ivServiceBottom.setBackground(getResources().getDrawable(R.drawable.shape_triangle_up));
                ivOwner.setImageResource(R.mipmap.owner_default);
                tvOwner.setTextColor(getResources().getColor(R.color.color_666666));
                ivOwnerBottom.setBackground(null);
                break;
            case R.id.rl_owner://业主
                companyTypeStr = "1";//标记号
                ivOwner.setImageResource(R.mipmap.owner_selected);
                tvOwner.setTextColor(getResources().getColor(R.color.blue_color));
                ivOwnerBottom.setBackground(getResources().getDrawable(R.drawable.shape_triangle_up));
                ivService.setImageResource(R.mipmap.service_default);
                tvService.setTextColor(getResources().getColor(R.color.color_666666));
                ivServiceBottom.setBackground(null);
                break;
            case R.id.btn_vercode://获取验证码
                String phone = etPhone.getText().toString().trim();
                if (!TextUtils.isEmpty(phone)) {
                    if (FormatUtil.isMobileNO(phone)) {
                        ServiceRequestManager.getManager().getRegisterCode(this, phone, this);
                        sendMessageClick();//发送验证码
                    } else {
                        showCenterInfoMsg("请输入正确的手机号码");
                    }
                } else {
                    showCenterInfoMsg("请输入手机号码");
                }
                break;
            case R.id.btn_register://注册按钮
                String enterpriseName = etEnterprise.getText().toString().trim();
                String Name = etName.getText().toString().trim();
                String mobilePhone = etPhone.getText().toString().trim();
                String vercode = etVerification.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();
                String determinePwd = etDeterminePwd.getText().toString().trim();
                boolean checked = cbProtocol.isChecked();
                if (!checked) {
                    showCenterInfoMsg("请阅读并同意《服务协议》");
                    return;
                }
                if (TextUtils.isEmpty(enterpriseName)) {
                    showCenterInfoMsg("请输入企业名称");
                    return;
                }
                if (TextUtils.isEmpty(Name)) {
                    showCenterInfoMsg("请输入用户名称");
                    return;
                }
                if (TextUtils.isEmpty(mobilePhone)) {
                    showCenterInfoMsg("请输入手机号");
                    return;
                }
                if (!FormatUtil.isMobileNO(mobilePhone)) {
                    showCenterInfoMsg("请输入正确手机号");
                    return;
                }
                if (TextUtils.isEmpty(vercode)) {
                    showCenterInfoMsg("请输入验证码");
                    return;
                }
                if (TextUtils.isEmpty(pwd)) {
                    showCenterInfoMsg("请输入密码");
                    return;
                }
                if (TextUtils.isEmpty(determinePwd)) {
                    showCenterInfoMsg("请输入确认密码");
                    return;
                }
                if (!pwd.equals(determinePwd)) {
                    showCenterInfoMsg("两次输入密码的不匹配");
                    return;
                }
                if (!FormatUtil.isPasswordFormat(determinePwd)) {
                    showCenterInfoMsg("密码格式不正确,密码限制在6-12位数字、字母的组合");
                    return;
                }
                userName = mobilePhone;
                password = determinePwd;
                HashMap map = new HashMap();
                map.put("companyName", enterpriseName);
                map.put("name", Name);
                map.put("mobilePhone", mobilePhone);
                map.put("password", determinePwd);
                map.put("vercode", vercode);
                map.put("companyType", companyTypeStr);
                ServiceRequestManager.getManager().register2Server(this, JsonMapUtil.mapToJson(map), this);
                break;
            default:
                break;
        }
    }

    //region 网网络请求回掉消息
    @Override
    public void onSuccess(int requestId, String result) {
        LogUtil.e("注册页面接口回掉 ：" + result);
        HashMap loginMap;
        switch (requestId) {
            case 11:
                CommonBean codeBean = new Gson().fromJson(result, CommonBean.class);
                if (codeBean != null && codeBean.getMessage() != null) {
                    if (codeBean.getMessage().getCode() == 200) {//成功  200
                        showCenterSuccessMsg("验证码获取成功");
                    } else {
                        showCenterInfoMsg(StringUtils.value(codeBean.getMessage().getMessage()));
                    }
                }
                break;
            case 12:
                CommonBean normalBean = new Gson().fromJson(result, CommonBean.class);
                if (normalBean.getMessage().getCode() == 200) {//成功  200
                    showCenterSuccessMsg("注册成功");
                    loginMap = new HashMap();
                    loginMap.put("userName", userName);
                    loginMap.put("password", password);
                    loginMap.put("companyCode", String.valueOf(normalBean.getRows()));
                    loginMap.put("companyType", companyTypeStr);
                    register2Login(loginMap);
                } else {//企业名称已被注册
                    showRegisterErrorMessage(normalBean.getMessage().getCode());
                }
                break;
            default:
                break;
        }
    }

    @Override    public void onException(int requestId, String code) {        showTopWrongMsg(getResources().getString(R.string.net_work_error));    }

    //显示提示消息
    public void showRegisterErrorMessage(int messageCode) {
        switch (messageCode) {
            case 201:
                showCenterInfoMsg("数据格式不正确");
                break;
            case 1001:
                showCenterInfoMsg("手机号码已被注册");
                break;
            case 1006:
                showCenterInfoMsg("企业名称已被注册");
                break;
            case 1005:
                showCenterInfoMsg("手机验证码不正确");
                break;
            default:
                break;
        }
    }

    //endregion

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {
            cbProtocol.setChecked(true);
        }
    }

    private void register2Login(HashMap loginMap) {
        finish();
        LoginActivity.openLoginActivityFirstLogin(this, JsonMapUtil.mapToJson(loginMap));
    }

    //region 发送验证码倒计时按钮
    private class RegisterHandler extends Handler {
        private final WeakReference<RegisterActivity> weakReference;

        public RegisterHandler(RegisterActivity activity) {
            weakReference = new WeakReference<RegisterActivity>(activity);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            RegisterActivity activity = weakReference.get();
            if (activity != null && msg != null) {
                if (btnVercode != null) {
                    switch (msg.what) {
                        case 0:
                            if (msg.arg1 == 0) {
                                btnVercode.setText("获取验证码");
                                btnVercode.setBackgroundColor(Color.parseColor("#689df8"));
                                btnVercode.setTextColor(Color.parseColor("#FFFFFF"));
                                btnVercode.setClickable(true);
                            } else {

                                btnVercode.setText("(" + StringUtils.value(msg.arg1) + ")秒");
                                btnVercode.setBackgroundColor(Color.parseColor("#b8bfcc"));
                                btnVercode.setClickable(false);
                            }
                            break;
                            default:
                            break;
                    }
                }
            }
        }
    }

    //监听按钮下直接调用即可
    private void sendMessageClick() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 59; i >= 0; i--) {
                    Message msg = myHandler.obtainMessage();
                    msg.arg1 = i;
                    myHandler.sendMessage(msg);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //endregion


    public static void openRegisterActivity(Context context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
